﻿$(document).ready(function () {
    dataTableInPage = showDataTable();
    groupTable = showGroupTable();
    edit_pannel = init_edit_pannel();
    group_edit_pannel = init_group_editpannel();
    group_list_pannel = init_group_listpannel();
    initPlupload();
    initButton();
});

// 显示表格
function showDataTable() {
    var dt = $('#dataTable').dataTable(
            { "bJQueryUI": true,
                "oLanguage": { "sUrl": "script/jquery-datatables-resouse/cn.txt" },
                "aoColumns": [{ "sClass": "center", "mDataProp": "Id", "width": 60 },
                        { "sClass": "center", "mDataProp": "Title" },
                        { "sClass": "center", "mDataProp": "Image" },
                        { "sClass": "center", "mDataProp": "Link" },
                        { "sClass": "center", "mDataProp": "Order" },
                        { "sClass": "center", "mDataProp": "CreatedTime", "width": 130 },
                        {
                            //自定义列
                            "mDataProp": "Id",
                            "width": 120,
                            "sClass": "center",
                            "bSearchable": false,
                            "bStorable": false,
                            "bStateSave": true,
                            "mRender": function (obj, display, fullData) {
                                return '<a href=\"#\" class="inlineButton" onclick=\"showEditpannel(1,' + obj + ');return false;\">编辑</a>&nbsp;&nbsp;<a href=\"#\" class="inlineButton" onclick=\"deleteBanner(' + obj + ');return false;\">删除</a>';
                            }
                        }],
                "bServerSide": true,
                "sAjaxSource": "BannerList.ashx",
                "bProcessing": true,
                "bPaginate": true,  //是否分页。
                "bSort": false,
                "sPaginationType": "full_numbers",
                "bSearchable": true,
                "bStateSave": true,
                "bFilter": true,
                "retrieve": true,
                "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                "fnDrawCallback": function () { $(".inlineButton").button(); $(".inlineButton").css("fontSize", "12px") },
                "fnServerParams": function (aoData) {
                    aoData.push({ "name": "groupId", "value": $("#slGroupNav").val() });
                }
            });
    return dt;
}

// 显示分组列表
function showGroupTable() {
    var dt = dataTableExt("BannerGroupList.ashx", "groupTable",
                [{ "sClass": "center", "mDataProp": "Id", "width": 60 },
                { "sClass": "center", "mDataProp": "Title" },
                { "sClass": "center", "mDataProp": "CreatedTime", "width": 180 },
                {
                    //自定义列
                    "mDataProp": "Id",
                    "width": 120,
                    "sClass": "center",
                    "bSearchable": false,
                    "bStorable": false,
                    "bStateSave": true,
                    "mRender": function (obj, display, fullData) {
                        return '<a href=\"#\" class="inlineButton" onclick=\"showGroupEditpannel(1,' + obj + ');return false;\">编辑</a>&nbsp;&nbsp;<a href=\"#\" class="inlineButton" onclick=\"deleteBannerGroup(' + obj + ');return false;\">删除</a>';
                    }
                }]);
    return dt;
}

// 初始化编辑幻灯片按钮
function init_edit_pannel() {
    var pannel = $("#edit_pannel").dialog({
        autoOpen: false,
        title: "编辑幻灯片",
        modal: true,
        buttons: {
            "确定": function () { saveBanner(); },
            "取消": function () { $(this).dialog("close"); }
        },
        width: 440
    });

    pannel.find("form").submit(function (event) {
        event.preventDefault();
        saveBanner();
    });
    return pannel;
}


//初始化分组面板
function init_group_editpannel() {
    var pannel = $("#group_edit_pannel").dialog({
        autoOpen: false,
        title: "编辑分组",
        modal: true,
        buttons: {
            "确定": function () { saveGroup(); },
            "取消": function () { $(this).dialog("close"); }
        },
        width: 380
    });

    pannel.find("form").submit(function (event) {
        event.preventDefault();
        saveGroup();
    });
    return pannel;
}

//初始化分组管理面板
function init_group_listpannel() {
    var pannel = $("#group_list_pannel").dialog({
        autoOpen: false,
        title: "分组管理",
        modal: true,
        buttons: {
            "取消": function () { $(this).dialog("close"); }
        },
        width: 600
    });
    return pannel;
}

/*o:当前的操作编码0：添加，1：修改，2：删除*/
function showEditpannel(o, id) {
    $("#hid_operation").val(o.toString());
    if (o == 0) {
        edit_pannel.title = "添加幻灯片";
        $("#hid_id").val("");
        $("#txt_title").val("");
        $("#txt_url").val("");
        $("#txt_order").val("");
        $("#slGroup").val("-1");
        $("#hid_imgpath").val("");
        $("#file-list li").remove();
    }
    else if (o == 1) {
        edit_pannel.title = "修改幻灯片";
        $.post("BannerHandler.ashx",
                   { o: 3, id: id },
                    function (data) {
                        if (!data) {
                            showDialog("应用程序内部错误");
                            return false;
                        }

                        if (data.State) {
                            $("#hid_id").val(id);
                            $("#txt_title").val(data.Data.Title);
                            $("#txt_url").val(data.Data.Link);
                            $("#txt_order").val(data.Data.Order);
                            $("#slGroup").val(data.Data.GroupID);
                            $("#hid_imgpath").val(data.Data.Image);
                            $("#file-list li").remove();
                            var html = '<li id="file-inbase"><div class="file-name">' + data.Data.Image + '</div></li>';
                            $(html).appendTo('#file-list');
                            $('#file-inbase').append('<div style="text-align:center;"> <img id="image-' + id + '" src="' + data.Data.Image.replace("~", applicationPath) + '" /></div>');

                            fitImageSize("image-" + id, 390, 200);
                        } else {
                            showDialog(data.Message);
                        }
                    },
                     "json");
    }
    edit_pannel.dialog("open");
    return false;
}

function saveBanner() {
    var o = $("#hid_operation").val();
    var id = $("#hid_id").val();
    var title = $("#txt_title").val();
    var url = $("#txt_url").val();
    var order = $("#txt_order").val();
    var groupId = $("#slGroup").val();
    var image = $("#hid_imgpath").val();
    $.post("BannerHandler.ashx",
            { o: o, id: id, title: title, url: url, order: order, groupId: groupId, image: image },
            function (data) {
                if (!data) {
                    showDialog("保存失败！");
                }
                else if (data.result) {
                    edit_pannel.dialog("close");
                    dataTableInPage.fnStandingRedraw();
                }
                else {
                    showDialog(data.msg);
                }
            },
            "json");
}

//删除幻灯片
function deleteBanner(id) {
    if (confirm("确定要删除此幻灯片吗？")) {
        $.post("BannerHandler.ashx",
                { o: 2, id: id },
                function (data) {
                    if (!data) {
                        showDialog("删除失败！");
                    }
                    else {
                        if (data.result) {
                            showDialog("删除成功！");
                            if (dataTableInPage) {
                                dataTableInPage.fnStandingRedraw();
                            }
                        }
                        else {
                            showDialog(data.msg);
                        }
                    }
                },
                "json");
    }
    return false;
}

//删除幻灯片分组
function deleteBannerGroup(id) {
    if (confirm("确定要删除此分组吗？")) {
        $.post("BannerGroupHandler.ashx",
                { o: 2, id: id },
                function (data) {
                    if (!data) {
                        showDialog("删除失败！");
                    }
                    else {
                        if (data.result) {
                            showDialog("删除成功！");
                            if (dataTableInPage) {
                                $("#slGroupNav option[value=" + id + "]").remove();
                                $("#slGroup option[value=" + id + "]").remove();
                                dataTableInPage.fnStandingRedraw();
                                groupTable.fnStandingRedraw();
                            }
                        }
                        else {
                            showDialog(data.msg);
                        }
                    }
                },
                "json");
    }
    return false;
}



// 保存分组
function saveGroup() {
    var grouptitle = $("#txt_groupTitle").val();
    var groupid = $("#hid_groupid").val();
    var groupOperation = $("#hid_group_operation").val();

    $.post("BannerGroupHandler.ashx",
            { o: groupOperation, id: groupid, title: grouptitle },
            function (data) {
                if (!data) {
                    showDialog("保存失败！");
                }
                else if (data.result) {
                    group_edit_pannel.dialog("close");
                    if (groupOperation == "0") {
                        $("#slGroupNav").append($("<option value='" + data.id + "'>" + grouptitle + "</option>"));
                        $("#slGroup").append($("<option value='" + data.id + "'>" + grouptitle + "</option>"));
                    }
                    else {
                        groupTable.fnStandingRedraw();
                        $("#slGroupNav option[value=" + groupid + "]").text(grouptitle);
                        $("#slGroup option[value=" + groupid + "]").text(grouptitle);
                    }
                }
                else {
                    showDialog(data.msg);
                }
            },
            "json");
}

//显示分组编辑面板。o->0:添加,1:编辑，2:删除，3.根据Id查询
function showGroupEditpannel(o, id) {
    var $grouptitle = $("#txt_groupTitle");
    var $groupid = $("#hid_groupid");
    $("#hid_group_operation").val(o);
    if (o == 0) {
        group_edit_pannel.title = "添加分组";
        $grouptitle.val("");
        $groupid.val("");
    }
    else if (o == 1) {
        group_edit_pannel.title = "编辑分组";
        $.post("BannerGroupHandler.ashx",
                   { o: 3, id: id },
                    function (data) {
                        if (!data) {
                            showDialog("应用程序内部错误");
                            return false;
                        }

                        if (data.State) {
                            $groupid.val(id);
                            $grouptitle.val(data.Data.Title);
                        } else {
                            showDialog(data.Message);
                            return false;
                        }
                    },
                     "json");
    }
    group_edit_pannel.dialog("open");
    return false;
}

// 初始化功能按钮
function initButton() {
    $("#addBannerBtn").click(function () {
        showEditpannel(0);
    });
    $("#addGroupBtn").click(function () {
        showGroupEditpannel(0);
    });
    $("#manageGroupBtn").click(function () {
        group_list_pannel.dialog("open");
    });
    $("#slGroupNav").change(function (event) {
        event.preventDefault();
        // 刷新dataTable
        dataTableInPage.fnStandingRedraw();
    });
}

// 初始化图片上传控件
function initPlupload() {
    uploader = new plupload.Uploader({
        browse_button: 'btnSelectImg', //触发文件选择对话框的按钮，为那个元素id
        url: 'ImageUploadHandler.ashx', //服务器端的上传页面地址
        flash_swf_url: 'script/plupload/Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
        silverlight_xap_url: 'script/plupload/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
        filters: {
            mime_types: [{ title: "图片文件", extensions: "jpg,gif,png"}], //只允许上传图片和zip文件 
            max_file_size: '2048kb', //最大只能上传2MB的文件
            prevent_duplicates: false //不允许选取重复文件
        },
        multi_selection: false,
        file_data_name: "file"
    }
            );

    //在实例对象上调用init()方法进行初始化
    uploader.init();

    //绑定文件添加进队列事件，只保留一个文件
    uploader.bind('FilesAdded', function (uploader, files) {
        $("#file-list li").remove();
        var times = uploader.files.length - 1;
        for (var i = 0; i < times; i++) {
            uploader.removeFile(uploader.files[0]);
        }

        for (var i = 0, len = uploader.files.length; i < len; i++) {
            var file_name = uploader.files[i].name; //文件名
            //构造html来更新UI
            var html = '<li id="file-' + uploader.files[i].id + '"><div class="file-name">' + file_name + '</div><div class="progress-bg"><div class="progress"></div></div></li>';
            $(html).appendTo('#file-list');
            !function (i) {
                previewImage(uploader.files[i], function (imgsrc) {
                    $('#file-' + uploader.files[i].id).append('<div style="text-align:center;"> <img src="' + imgsrc + '" /></div>');
                })
            } (i);
        }
    });

    //绑定文件上传进度事件
    uploader.bind('UploadProgress', function (uploader, file) {
        $('#file-' + file.id + ' .progress').css('width', file.percent + '%'); //控制进度条
    });

    //上传错误
    uploader.bind('Error', function (uploader, errObject) {
        if (errObject.code == -600) {
            showDialog("请选择小于2M的图片文件（jpg,gif,png）上传。", "提示", 170); //提示错误
        }
        else {
            showDialog(errObject.message);
        }
    });

    //上传完成
    uploader.bind('FileUploaded', function (uploader, file, responseObject) {
        var serverRsponse = eval('(' + responseObject.response + ')');
        if (responseObject.status == 200) {
            if (serverRsponse.result) {
                $("#hid_imgpath").val(serverRsponse.virtualPath);
                showDialog("上传成功");
            }
            else {
                showDialog(serverRsponse.message, "提示", 200);
            }
        }
        else {
            showDialog("上传服务器出错");
        }
    });

    //上传按钮
    $('#btnUpload').click(function (event) {
        event.preventDefault();
        uploader.start(); //开始上传
    });

    function previewImage(file, callback) {
        //file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
        if (!file || !/image\//.test(file.type)) return; //确保文件是图片
        if (file.type == 'image/gif') {
            //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
            var fr = new mOxie.FileReader();
            fr.onload = function () {
                callback(fr.result);
                fr.destroy();
                fr = null;
            }
            fr.readAsDataURL(file.getSource());
        } else {
            var preloader = new mOxie.Image();
            preloader.onload = function () {
                preloader.downsize(390, 200); //先压缩一下要预览的图片,宽390，高200
                var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
                callback && callback(imgsrc); //callback传入的参数为预览图片的url
                preloader.destroy();
                preloader = null;
            };
            preloader.load(file.getSource());
        }
    }
}